﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;


using System.Runtime.Serialization.Json;
using Server;


namespace Client
{
    public class WeatherItemClass
    {
        public String description { get; set; }
        public double highTemp { get; set; }
        public double lowTemp { get; set; }
        public override string ToString()
        {
            return description + "," + lowTemp.ToString() + "," + highTemp.ToString();
        }
    }

    public class WeatherClass
    {
        public String city { get; set; }
        public String date { get; set; }
        public WeatherItemClass weather { get; set; }
        public override string ToString()
        { return city + "," + date + "," + weather.ToString(); }
    }
    public class GZipWebClient : WebClient
    {
        protected override WebRequest GetWebRequest(Uri address)
        {
            HttpWebRequest webrequest = (HttpWebRequest)base.GetWebRequest(address);
            webrequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            return webrequest;
        }
    }
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        //获取密钥
        String key = Properties.Resources.key;
        //反序列化解析
        T deserializejson<T>(String s)
        {
            //天气的 JSON 数据解析为 Rootobject 类型
            DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(T));
            byte[] buf = Encoding.UTF8.GetBytes(s);
            MemoryStream ms = new MemoryStream(buf);
            T obj = (T)json.ReadObject(ms);
            return obj;
        }

        
        String city = "";
        //点击按钮调用接口
        
        private void button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //WebClient client = new WebClient(); 
                GZipWebClient client = new GZipWebClient();
                //client.Encoding = Encoding.UTF8; 
                client.Encoding = Encoding.GetEncoding("GB2312");
                //client.DownloadStringCompleted += Client_DownloadStringCompleted; 
                client.DownloadDataCompleted += Client_DownloadDataCompleted;
                string url = "https://devapi.qweather.com/v7/weather/now?location=101200101"
                + "&key=" + key;// 101200101为武汉id 
                Uri uri = new Uri(url, UriKind.Absolute);
                //client.DownloadStringAsync(uri); 
                //异步请求数据，不阻塞主线程。请求完成后，触发 Client_DownloadDataCompleted 事件
                client.DownloadDataAsync(uri);
                txt.Text = "等待服务器响应...";
            }
            catch (Exception exp)
            {
                txt.Text = exp.Message;
            }
        }
        //异步请求后调用的函数
        private void Client_DownloadDataCompleted(object sender,DownloadDataCompletedEventArgs e)
        {
            //将获取的字节流（e.Result）转换为字符串（s）并反序列化为 Rootobject 对象
            try
            {
                MemoryStream ms = new MemoryStream(e.Result);
                string s = Encoding.UTF8.GetString(e.Result);
                //调用deserializejson函数解析,设置泛型Rootobject
                Rootobject w = deserializejson<Rootobject>(s);
                txt.Text = "\r\n" + w.now.ToString();
            }
            catch (Exception exp)
            {
                txt.Text = exp.Message;
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            cbCity.Items.Add("选择");
            cbCity.Items.Add("北京");
            cbCity.Items.Add("上海");
            cbCity.Items.Add("深圳");
            cbCity.Items.Add("武汉");
            cbCity.SelectedIndex = 0;
        }
        private void cbCity_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                String city = cbCity.SelectedItem.ToString();
                switch (city)
                {
                    case "北京":
                        city = "101010100";
                        break;
                    case "上海":
                        city = "101020100";
                        break;
                    case "深圳":
                        city = "101280601";
                        break;
                    case "武汉":
                        city = "101200101"; break;
                    default:
                        city = "";
                        break;
                } //WebClient client = new WebClient(); 
                GZipWebClient client = new GZipWebClient();
                //client.Encoding = Encoding.UTF8; 
                client.Encoding = Encoding.GetEncoding("GB2312");
                //client.DownloadStringCompleted += Client_DownloadStringCompleted; 
                client.DownloadDataCompleted += Client_DownloadDataCompleted; ;
                string url = "https://devapi.qweather.com/v7/weather/now?location=" +city + "&key=" + key;
                Uri uri = new Uri(url, UriKind.Absolute);
                //client.DownloadStringAsync(uri); 
                client.DownloadDataAsync(uri, city);
                
                if (city == ""&&city==null)
                {
                    txt.Text = "请选择...";
                }
                else { txt.Text = "等待服务器响应..."; }
            }
            catch (Exception exp)
            {
                txt.Text = exp.Message;
            }
        }

        public MainWindow()
        {
            InitializeComponent();
        }

        void showMsg(String s)
        {
            MessageBox.Show(s, "Information",MessageBoxButton.OK);
        }

    }

}



